package com.example.tiantian.application;

import java.util.List;

import com.example.tiantian.R;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class AppAdapter extends BaseAdapter {

    Context context;
    LayoutInflater inflater;
    List<ApplicationInfo> apps;
    boolean isGrid;
    PackageManager packageManager;

    public AppAdapter(Context context, List<ApplicationInfo> apps, boolean isGrid, PackageManager packageManager) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.apps = apps;
        this.isGrid = isGrid;
        this.packageManager = packageManager;
    }

    @Override
    public int getCount() {
        return apps.size();
    }

    @Override
    public ApplicationInfo getItem(int position) {
        return apps.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        class Views {
            ImageView imgIcon;
            TextView txtName;
            TextView txtPackageName;

            public Views(View v) {
                imgIcon = (ImageView) v.findViewById(R.id.app_item_image);
                txtName = (TextView) v.findViewById(R.id.app_item_name);
                txtPackageName = (TextView) v.findViewById(R.id.app_item_package_name);
            }
        }
        Views views = null;
        if (convertView == null || (Boolean) convertView.getTag(3 << 24) != isGrid) {
            convertView = inflater.inflate(isGrid ? R.layout.app_item_grid : R.layout.app_item_list, null);
            views = new Views(convertView);
            convertView.setTag(3 << 24, Boolean.valueOf(isGrid));
            convertView.setTag(4 << 24, views);
        } else {
            views = (Views) convertView.getTag(4 << 24);
        }
        ApplicationInfo info = getItem(position);
        views.imgIcon.setImageDrawable(info.loadIcon(packageManager));
        views.txtName.setText(info.loadLabel(packageManager));
        views.txtPackageName.setText(info.packageName);
        return convertView;
    }

    public void changeShowType(boolean isGrid) {
        this.isGrid = isGrid;
    }

    public void changeAppList(List<ApplicationInfo> apps) {
        this.apps = apps;
    }
}
